﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;
using System.Text;

namespace DeviceCommons.DeviceMessages.Serialization.V2.Parsers
{
    public class DeviceMessageChildParser : AbstractMessageParser<IDeviceMessageChild>, IDeviceMessageChildParser, IContextAwareParser
    {
        private ParsingContext? _context;

        public DeviceMessageChildParser() : base(new DeviceMessageChild())
        {
        }

        public override IDeviceMessageChild Parser(ReadOnlySpan<byte> bytes)
        {
            byte count = bytes[0];
            IDeviceMessageChild model = new DeviceMessageChild();
            var childArray = new IDeviceMessageInfo[count];
            var bytesTemp = bytes[1..];
            for (int i = 0; i < count; i++)
            {
                // 设置上下文到子解析器
                if (_context != null && DeviceMessageSerializerProvider.InfoV2Par is IContextAwareParser contextAwareParser)
                {
                    contextAwareParser.SetContext(_context);
                }
                
                childArray[i] = DeviceMessageSerializerProvider.InfoV2Par.Parser(bytesTemp);
                bytesTemp = bytesTemp[childArray[i].DataLength..];
            }
            model.ChildArray = childArray;
            Model = model;
            return model;
        }

        public void SetContext(ParsingContext context)
        {
            _context = context;
        }

        public ParsingContext? GetContext()
        {
            return _context;
        }
    }
}
